import React, { Component } from 'react';
import { connect } from "react-redux";
import { getUserInfoAction } from "../../store/actions/SettingAction"
import { withRouter } from "react-router-dom"
import "./SetUserName.scss"
import store from "../../store"
import { updateName } from "../../data/set"
import { Toast } from "antd-mobile"

class SetUerName extends Component {
  state = {
    username: '',
    clear: ''
  }
  submitName = async () => {
    if (this.state.username === "") {
      Toast.info("请输入姓名")
    } else {
      let username = encodeURIComponent(this.state.username)
      await updateName(username)
      await store.dispatch(getUserInfoAction())
      this.props.history.push('set')
    }
  }
  handlechange = () => {
    if (this.state.username !== '') {
      this.setState({
        clear: 'appear'
      })
    } else {
      this.setState({
        clear: ''
      })
    }
  }
  clearname = async () => {
    this.setState({
      username: ''
    })
  }
  changename = async (e) => {
    if (e.target.value !== '') {
      await this.setState({
        clear: 'appear',
        username: e.target.value
      })
    } else {
      await this.setState({
        clear: '',
        username: e.target.value
      })
    }
  }
  blur = async () => {
    await this.setState({
      clear: ''
    })
  }
  toSet=()=>{
    this.props.history.push('set')
  }
  render() {
    return (
      <div className="setUserName">
        <div className="UNTitle">
          <div className="titleBack" onClick={this.toSet}><i className="iconfont icon-youjiankuohao"></i></div>
          <div className="titlecontent">修改姓名</div>
          <div className="titleBlock"></div>
        </div>
        <div className="UNName">
          <div className="UNNameLeft">
            <i>*</i>
            <span>用户名</span>
          </div>
          <input onBlur={this.blur} type="text" onClick={this.handlechange} className="UNNameRight" value={this.state.username} onChange={this.changename.bind(this)} placeholder="请输入"></input>
          <div className={this.state.clear === "appear" ? 'clear appear' : 'clear'}>
            <span onClick={this.clearname}>X</span>
          </div>
        </div>
        <div className="submit" onClick={this.submitName}>确定</div>
      </div >
    );
  }
  async componentDidMount() {
    await store.dispatch(getUserInfoAction())
    await this.setState({
      username: decodeURIComponent(this.props.userMessage.data.nickName)
    })
  }
}
const mapStateToProps = (state) => {
  return {
    userMessage: state.SettingReducer.userMessage,
  }
}

export default connect(mapStateToProps, null)(withRouter(SetUerName));
